package com.seven.netty.protocol.server;

import com.seven.netty.protocol.codec.MessageDecoder;
import com.seven.netty.protocol.codec.MessageEncoder;
import com.seven.netty.protocol.handler.ServerHeartBeatHandler;
import com.seven.netty.protocol.handler.MessageHandler;
import com.seven.netty.protocol.handler.ResponseHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author chendongdong
 * @description TCP服务类
 * @since 2024/3/6 10:47
 */
@Slf4j
@Component
public class TcpServer implements CommandLineRunner {
    @Value("${tcp.server.port:9000}")
    private int port = 9000;

    @Override
    public void run(String... args) throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap
                .group(boss, work)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline()
                            .addLast(new IdleStateHandler(60,0,0, TimeUnit.SECONDS))
                            .addLast(new MessageDecoder())
                            .addLast(new MessageEncoder())
                            .addLast(new ServerHeartBeatHandler())
                            .addLast(new MessageHandler())
                            .addLast(new ResponseHandler());

                    }
                });
            log.info("tcp server start success, port is {}", port);
            ChannelFuture future = bootstrap.bind(port).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("tcp server start fail:", e);
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }
    }
}
